package com.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;


@Configuration
@MapperScan({"com.dao", "com.dao.ums"})
public class DBConfig {
    
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//        Resource resource = new PathMatchingResourcePatternResolver().getResource("classpath*:mapper/*.xml");
//        sqlSessionFactoryBean.setMapperLocations(new Resource[]{resource});
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources;
        try {
            resources = resolver.getResources("classpath*:mapper/*.xml");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        sqlSessionFactoryBean.setMapperLocations(resources);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setLogImpl(StdOutImpl.class);
//        configuration.addCache(new RedisCache());
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

//    @Bean
//    public SqlSessionFactory sqlSessionFactory(SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
//        SqlSessionFactory object = sqlSessionFactoryBean.getObject();
//        System.out.println();
//        return null;
//    }
    @Bean
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("Zhangpingyang@123");
        dataSource.setJdbcUrl("jdbc:mysql://rm-wz9okfspb8atf5s716o.mysql.rds.aliyuncs.com:3306/mall?useSSL=false&useUnicode=true&autoReconnect=true&rewriteBatchedStatements=true");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return dataSource;
//        DriverManagerDataSource da = new DriverManagerDataSource();
//        da.setUrl("jdbc:mysql://rm-wz9okfspb8atf5s716o.mysql.rds.aliyuncs.com:3306/mall?useUnicode=true&autoReconnect=true&rewriteBatchedStatements=true");
//        da.setUsername("root");
//        da.setPassword("Zhangpingyang@123");
//        da.setDriverClassName("com.mysql.jdbc.Driver");
//        return da;
    }
}
